global.BodyData = db.collection("Menstruation.BodyData");
// 开始时间、疼痛指数、间隔（周期）
// 持续时长、状况、结束时间
module.exports = {
    get: function(req, res) {
        co(function*() {
            var dataCount = (yield BodyData.count()) || 1;
            var getlength;
            console.log(dataCount);
            (dataCount > 1) ? getlength = 2: getlength = 1;
            var doc = yield BodyData.find({}).skip(dataCount - getlength).limit(getlength).toArray();

            // console.log(doc)
            console.log("get~!!!");
            console.log(doc);
            console.log("get~!!!");
            res.send(doc || {});
        }).catch(e => {
            console.log(e);
        });
    },
    post: function(req, res) {
        var bodyData = req.body;
        co(function*(argument) {
            var dataCount = (yield BodyData.count()) || 1;
            var doc = yield BodyData.find({}).skip(dataCount - 1).limit(1).toArray();
            doc = doc[0];
            doc ? (bodyData.cycle = ~~((bodyData.starttime - doc.starttime) / 1000 / 60 / 60 / 24)) : bodyData.cycle = 0;
            BodyData.insertOne(bodyData);
            console.log("post~!!!");
            console.log(bodyData);
            console.log("post~!!!");
            res.send(bodyData);
        }).catch(e => {
            console.loe(e);
            res.end();
        });
    },
    put: function(req, res) {
        var bodyData = req.body;
        var _id = new ObjectId(bodyData._id);
        // var _id = bodyData._id;
        bodyData.endtime = new Date().getTime();
        bodyData.status = "regular";
        co(function*() {
            var dataCount = (yield BodyData.count()) || 1;
            if (dataCount == 1) {
                bodyData.period = 0;
            } else {
                var doc = yield BodyData.find({}).skip(dataCount - 2).limit(1).toArray();
                doc = doc[0];
                bodyData.period = ~~((bodyData.endttime - doc.starttime) / 1000 / 60 / 60 / 24);
            };
            delete bodyData._id;
            var r = yield BodyData.findOneAndUpdate({ _id: _id }, { $set: bodyData }, { upsert: true, returnOriginal: false });
            console.log("put~!!!");
            console.log(bodyData);
            console.log("put~!!!");
            res.send(bodyData);
        }).catch(e => {
            console.log("what")
            console.log(e);
            res.end();
        });
    }
}
